package com.jpatest.demo.Redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisTemplate;

public class TwoLevelCacheManager extends RedisCacheManager {
    RedisTemplate redisTemplate;
    public TwoLevelCacheManager(RedisTemplate redisTemplate, RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
        this.redisTemplate = redisTemplate;
    }

    public void pulishMessage(String flag, String cacheName, Object key){
        JSONObject json = new JSONObject();
        json.put("flag",flag);
        json.put("key",key);
        json.put("name",cacheName);
        String jsonString = JSON.toJSONString(json);
        this.redisTemplate.convertAndSend("SpringRedisCache", jsonString);
    }

    @Override
    protected Cache decorateCache(Cache cache){
        return new RedisAndLocalCache((RedisCache)cache, this);
    }

    //接收一个消息更新或者清空本地缓存
    public void receiver(JSONObject json){
        RedisAndLocalCache cache = (RedisAndLocalCache)this.getCache((String)json.get("name"));
        if(cache!=null){
            if(json.get("flag").equals("update")){
                 cache.updateLocal(json.get("key"));
            }else{
                cache.clearLocal(json.get("key"));
            }
        }
    }
}
